//
//  RecommendController.m
//  敢唆嘛!
//
//  Created by 教主 on 15/11/26.
//  Copyright © 2015年 zms. All rights reserved.
//

#import "RecommendController.h"
#import "Device.h"
#import "RecommendView.h"
#import "ChineseToPinyin.h"

@interface RecommendController ()
@property(nonatomic, strong)RecommendView *recommendView;
@property(nonatomic, strong)BmobUser *bmobUser;         // 用户
@end

@implementation RecommendController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    // 添加标题
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0 , 0, KSWidth / 8, KSWidth / 28)];
    titleLabel.text = @"推荐故事";
    titleLabel.alpha = 0.8;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont systemFontOfSize:KSWidth / 22];
    self.navigationItem.titleView = titleLabel;
    
    [self.navigationController.navigationBar setTintColor:[UIColor colorWithRed:18 / 255.0 green:182 / 255.0 blue:168 / 255.0 alpha:1.0]];
    // 添加左上角取消按钮
    UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelBtnAction:)];
    self.navigationItem.leftBarButtonItem = cancelBtn;
    
    // 添加右上角推荐按钮
    UIBarButtonItem *recommendBtn = [[UIBarButtonItem alloc] initWithTitle:@"推荐" style:UIBarButtonItemStylePlain target:self action:@selector(recommendBtnAction:)];
    self.navigationItem.rightBarButtonItem = recommendBtn;
    //自定义视图
    self.recommendView = [[RecommendView alloc] initWithFrame:CGRectMake(0, 0, KSWidth, KSHeight - 64)];
    [self.view addSubview:_recommendView];
    
    // 赋值
    if (self.homeModel)
    {
        [_recommendView setHomeModel:self.homeModel];
    }
    else
    {
        [_recommendView setRealityModel:self.realityModel];
    }
    
}

// 点击推荐按钮触发
- (void)recommendBtnAction:(UIBarButtonItem *)recommendBtn
{
    // 不为0 说明有内容
    if (_recommendView.recommendTextView.text.length != 0)
    {
        // 把被推荐的人 和 推荐者 数据存入主页数据库内
        [self addHomeTableData];
    }
    else
    {
        // 提示
        [self promptViewWithTitle:@"推荐语不能不写哟~" buttonEnabled:self.navigationItem.rightBarButtonItem];
    }
}

// 把被推荐的人 和 推荐者 数据存入主页数据库内
- (void)addHomeTableData
{
    // 获取当前登录的用户
    self.bmobUser = [BmobUser getCurrentUser];
    BmobObject *recommendHome = [BmobObject objectWithClassName:@"RecommendHome"];
    
    [recommendHome setObject:_bmobUser.username forKey:@"recommendUserName"];
    [recommendHome setObject:self.recommendView.recommendTextView.text forKey:@"recommendInfoTitle"];
    if (self.homeModel)
    {
        [recommendHome setObject:self.homeModel.userName forKey:@"userName"];
        [recommendHome setObject:self.homeModel.infoTitle forKey:@"infoTitle"];
        [recommendHome setObject:self.homeModel.info forKey:@"info"];
        [recommendHome setObject:self.homeModel.type forKey:@"type"];
        [recommendHome setObject:self.homeModel.realityObjectId forKey:@"realityObjectId"];
//        [recommendHome setObject:self.homeModel.realityCreatedAt forKey:@"realityCreatedAt"];
        [recommendHome saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
            //进行操作
            if (isSuccessful)
            {
                NSLog(@"成功");
                // 根据用户名添加一个推荐表和数据
                [self addUserRecommendHomeTable];
            }
            else
            {
                NSLog(@"失败");
                NSLog(@"%@",error);
            }
        }];
    }
    else
    {
        [recommendHome setObject:self.realityModel.userName forKey:@"userName"];
        [recommendHome setObject:self.realityModel.infoTitle forKey:@"infoTitle"];
        [recommendHome setObject:self.realityModel.info forKey:@"info"];
        [recommendHome setObject:self.realityModel.type forKey:@"type"];
        [recommendHome setObject:self.realityModel.objectId forKey:@"realityObjectId"];
        [recommendHome saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
            //进行操作
            if (isSuccessful)
            {
                NSLog(@"成功");
                // 根据用户名添加一个推荐表和数据
                [self addUserRecommendHomeTable];
                
            }
            else
            {
                NSLog(@"失败");
                NSLog(@"%@",error);
            }
        }];
    }
}

// 根据用户名添加一个收藏表和数据
- (void)addUserRecommendHomeTable
{
    // 获取当前登录的用户
    self.bmobUser = [BmobUser getCurrentUser];
    // 把名字转化为拼音
    NSString *string = [ChineseToPinyin pinyinFromChiniseString:_bmobUser.username];
    //根据用户名添加一个该用户单独的推荐表
    BmobObject *userRecommend = [BmobObject objectWithClassName:[NSString stringWithFormat:@"%@Recommend",string]];
    [userRecommend setObject:_bmobUser.username forKey:@"recommendUserName"];
    [userRecommend setObject:self.recommendView.recommendTextView.text forKey:@"recommendInfoTitle"];
    if (self.homeModel)
    {
        [userRecommend setObject:self.homeModel.userName forKey:@"userName"];
        [userRecommend setObject:self.homeModel.infoTitle forKey:@"infoTitle"];
        [userRecommend setObject:self.homeModel.info forKey:@"info"];
        [userRecommend setObject:self.homeModel.realityObjectId forKey:@"realityObjectId"];
        [userRecommend setObject:self.homeModel.realityCreatedAt forKey:@"realityCreatedAt"];
        [userRecommend saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
            //进行操作
            if (isSuccessful)
            {
                NSLog(@"成功");
                // 弹出对话框提示
                [self promptViewWithTitle:@"推荐成功咯~" buttonEnabled:self.navigationItem.rightBarButtonItem];
                // 更新 reality表内的指定主题的推荐数
                [self updateRealityTableRecommend];
            }
            else
            {
                NSLog(@"失败");
                NSLog(@"%@",error);
                [self promptViewWithTitle:@"推荐失败咯~" buttonEnabled:self.navigationItem.rightBarButtonItem];
            }
        }];
    }
    else
    {
        [userRecommend setObject:self.realityModel.userName forKey:@"userName"];
        [userRecommend setObject:self.realityModel.infoTitle forKey:@"infoTitle"];
        [userRecommend setObject:self.realityModel.info forKey:@"info"];
        [userRecommend setObject:self.realityModel.objectId forKey:@"realityObjectId"];
        [userRecommend setObject:self.realityModel.createdAt forKey:@"realityCreatedAt"];
        [userRecommend saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
            //进行操作
            if (isSuccessful)
            {
                NSLog(@"成功");
                // 弹出对话框提示
                [self promptViewWithTitle:@"推荐成功咯~" buttonEnabled:self.navigationItem.rightBarButtonItem];
                // 更新 reality表内的指定主题的推荐数
                [self updateRealityTableRecommend];
            }
            else
            {
                NSLog(@"失败");
                NSLog(@"%@",error);
                [self promptViewWithTitle:@"推荐失败咯~" buttonEnabled:self.navigationItem.rightBarButtonItem];
            }
        }];
    }
}

// 更新 reality表内的指定主题的推荐数
- (void)updateRealityTableRecommend
{
    NSString *collectObjectId = nil;
    if (self.homeModel)
    {
        collectObjectId = self.homeModel.realityObjectId;
    }
    else
    {
        collectObjectId = self.realityModel.objectId;
    }

    // 先获取到本来的收藏数是多少
    BmobQuery *bquery = [BmobQuery queryWithClassName:[self tableClassName]];
    [bquery getObjectInBackgroundWithId:collectObjectId block:^(BmobObject *object,NSError *error){
        if (error){
            //进行错误处理
        }else{
            if (object)
            {
                // 得到该条数据当前的收藏数是多少
                NSInteger number = [[object objectForKey:@"recommendNumber"] integerValue] + 1;
                NSNumber *recommendNumber = [NSNumber numberWithInteger:number];
                // 修改值
                BmobObject *bmobObject = [BmobObject objectWithoutDatatWithClassName:[self tableClassName]  objectId:collectObjectId];
                [bmobObject setObject:recommendNumber forKey:@"recommendNumber"];
                [bmobObject updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                    if (isSuccessful) {
                        //修改成功后的动作
                        // 推荐数更新成功
                        NSLog(@"推荐数更新+1");
                        // 延迟0.5秒后回上一级界面
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [self.navigationController popViewControllerAnimated:YES];
                        });
                    } else if (error){
                        NSLog(@"%@",error);
                    } else {
                        NSLog(@"UnKnow error");
                    }
                }];
            }
        }
    }];
}

// 返回是哪个表的数据
- (NSString *)tableClassName
{
    NSString *className = nil;
#warning 判断页面
    if (self.homeModel)
    {
        if ([self.homeModel.type isEqualToString:@"真事"])
        {
            className = @"Reality";
        }
        else if ([self.homeModel.type isEqualToString:@"创作"])
        {
            className = @"Creation";
        }
        else if ([self.homeModel.type isEqualToString:@"游记"])
        {
            className = @"Travel";
        }
        else if ([self.homeModel.type isEqualToString:@"秘密"])
        {
            className = @"Secret";
        }
    }
    else
    {
        if ([self.realityModel.type isEqualToString:@"真事"])
        {
            className = @"Reality";
        }
        else if ([self.realityModel.type isEqualToString:@"创作"])
        {
            className = @"Creation";
        }
        else if ([self.realityModel.type isEqualToString:@"游记"])
        {
            className = @"Travel";
        }
        else if ([self.realityModel.type isEqualToString:@"秘密"])
        {
            className = @"Secret";
        }
    }
    return className;
}


// 取消按钮触发
- (void)cancelBtnAction:(UIBarButtonItem *)cancelBtn
{
    [self.navigationController popViewControllerAnimated:YES];
}

// 弹出提示窗口
- (void)promptViewWithTitle:(NSString *)title buttonEnabled:(UIBarButtonItem *)buttonEnabled
{
    // 关闭按钮交互
    buttonEnabled.enabled = NO;
    UIView *promptView = [[UIView alloc] initWithFrame:CGRectMake(((KSWidth - (KSWidth / 2)) / 2) * 2, 0, KSWidth / 2, KSWidth / 4)];
    promptView.backgroundColor = [UIColor whiteColor];
    promptView.alpha = 0;
    promptView.layer.cornerRadius = 10;
    promptView.layer.borderColor = [UIColor colorWithRed:150 / 255.0 green:150 / 255.0 blue:150 / 255.0 alpha:1.0].CGColor;
    promptView.layer.borderWidth = 1;
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(((KSWidth - (KSWidth / 2)) / 2) * 2, 0, KSWidth / 2, KSWidth / 4)];
    titleLabel.text = title;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.font = [UIFont systemFontOfSize:KSWidth / 25];
    titleLabel.alpha = 0;
    [self.view addSubview:promptView];
    [self.view addSubview:titleLabel];
    
    [UIView animateWithDuration:0.4 animations:^{
        promptView.alpha = 0.8;
        titleLabel.alpha = 0.8;
        promptView.frame = CGRectMake((KSWidth - (KSWidth / 1.2)) / 2, KSWidth - KSWidth / 1.35, KSWidth / 1.2, KSWidth / 4);
        titleLabel.frame = CGRectMake((KSWidth - (KSWidth / 1.2)) / 2, KSWidth - KSWidth / 1.35, KSWidth / 1.2, KSWidth / 4);
    }completion:^(BOOL finished) {
        // 延迟一秒
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:0.4 animations:^{
                promptView.alpha = 0;
                titleLabel.alpha = 0;
                promptView.frame = CGRectMake(((KSWidth - (KSWidth / 2)) / 2) * 2, 0, KSWidth / 2, KSWidth / 4);
                titleLabel.frame = CGRectMake(((KSWidth - (KSWidth / 2)) / 2) * 2, 0, KSWidth / 2, KSWidth / 4);
            }completion:^(BOOL finished) {
                // 打开收藏按钮交互
                buttonEnabled.enabled = YES;
                [promptView removeFromSuperview];
                [titleLabel removeFromSuperview];
            }];
        });
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
